/**
 * AssistantCard - Individual Assistant Card Component
 * 
 * Displays a single assistant with:
 * - Icon/Avatar
 * - Name
 * - Description
 * - Category badge
 * - Builtin badge
 * - Favorite indicator
 */

import {
  Bot,
  Star,
  Code,
  Database,
  FileText,
  Globe,
  Shield,
  TestTube,
  Palette,
  Server,
  Zap,
  Brain,
  Terminal,
  type LucideIcon,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { cn } from '@/lib/utils';

export interface Assistant {
  id: string;
  name: string;
  description: string;
  category?: string;
  isBuiltin?: boolean;
  isFavorite?: boolean;
  lastUsed?: number;
  sessionCount?: number;
  icon?: string; // Icon name or emoji
  iconColor?: string; // Custom icon background color
}

interface AssistantCardProps {
  assistant: Assistant;
  selected?: boolean;
  onClick?: () => void;
  onToggleFavorite?: (id: string) => void;
  compact?: boolean;
}

const categoryColors: Record<string, string> = {
  development: 'bg-blue-500/10 text-blue-500',
  testing: 'bg-green-500/10 text-green-500',
  security: 'bg-red-500/10 text-red-500',
  documentation: 'bg-purple-500/10 text-purple-500',
  database: 'bg-yellow-500/10 text-yellow-500',
  analysis: 'bg-orange-500/10 text-orange-500',
  devops: 'bg-cyan-500/10 text-cyan-500',
  design: 'bg-pink-500/10 text-pink-500',
};

const categoryLabels: Record<string, string> = {
  development: '开发',
  testing: '测试',
  security: '安全',
  documentation: '文档',
  database: '数据库',
  analysis: '分析',
  devops: 'DevOps',
  design: '设计',
};

// Icon mapping for assistants
const iconMap: Record<string, LucideIcon> = {
  bot: Bot,
  code: Code,
  database: Database,
  file: FileText,
  globe: Globe,
  shield: Shield,
  test: TestTube,
  palette: Palette,
  server: Server,
  zap: Zap,
  brain: Brain,
  terminal: Terminal,
};

// Default icons by category
const categoryIcons: Record<string, LucideIcon> = {
  development: Code,
  testing: TestTube,
  security: Shield,
  documentation: FileText,
  database: Database,
  analysis: Brain,
  devops: Server,
  design: Palette,
};

export function AssistantCard({
  assistant,
  selected = false,
  onClick,
  onToggleFavorite,
  compact = false,
}: AssistantCardProps) {
  const categoryColor = assistant.category 
    ? categoryColors[assistant.category] || 'bg-gray-500/10 text-gray-500'
    : 'bg-gray-500/10 text-gray-500';

  const categoryLabel = assistant.category
    ? categoryLabels[assistant.category] || assistant.category
    : '其他';

  return (
    <button
      onClick={onClick}
      className={cn(
        'group relative w-full text-left p-3 rounded-xl',
        'transition-all duration-200 ease-in-out',
        'border border-transparent',
        'hover:bg-gradient-to-br hover:from-accent/50 hover:to-accent/30',
        'hover:shadow-md hover:border-primary/20',
        'hover:-translate-y-0.5',
        'active:scale-[0.98]',
        selected && 'bg-gradient-to-br from-primary/10 to-primary/5 border-l-2 border-primary shadow-md',
        compact && 'p-2'
      )}
    >
      <div className="flex items-start gap-3">
        {/* Enhanced Avatar/Icon */}
        <Avatar className={cn(
          'shrink-0 shadow-sm',
          compact ? 'w-8 h-8' : 'w-12 h-12'
        )}>
          <AvatarFallback className={cn(
            'bg-gradient-to-br',
            assistant.iconColor || 'from-blue-500 to-purple-600',
            'text-white font-semibold'
          )}>
            {(() => {
            // 1. Try custom icon from assistant.icon
            if (assistant.icon) {
              const IconComponent = iconMap[assistant.icon];
              if (IconComponent) {
                return (
                  <IconComponent className={cn(
                    assistant.iconColor ? 'text-white' : 'text-primary',
                    compact ? 'w-3 h-3' : 'w-4 h-4'
                  )} />
                );
              }
              // If it's an emoji, display it directly
              if (assistant.icon.match(/[\p{Emoji}]/u)) {
                return <span className={compact ? 'text-base' : 'text-2xl'}>{assistant.icon}</span>;
              }
            }
            
            // 2. Try category-based icon
            if (assistant.category) {
              const CategoryIcon = categoryIcons[assistant.category];
              if (CategoryIcon) {
                return (
                  <CategoryIcon className={cn(
                    'text-white',
                    compact ? 'w-4 h-4' : 'w-6 h-6'
                  )} />
                );
              }
            }
            
            // 3. Default: Use first letter of name
            return (
              <span className={compact ? 'text-sm' : 'text-lg'}>
                {assistant.name[0]}
              </span>
            );
          })()}
        </AvatarFallback>
        </Avatar>

        {/* Enhanced Content */}
        <div className="flex-1 min-w-0">
          {/* Name */}
          <div className="flex items-center gap-2 mb-1">
            <span className={cn(
              'font-semibold truncate',
              'group-hover:text-primary transition-colors',
              compact ? 'text-sm' : 'text-base'
            )}>
              {assistant.name}
            </span>
            
            {assistant.isBuiltin && (
              <Badge 
                variant="secondary" 
                className={cn(
                  'px-1.5 py-0.5 text-[10px] font-medium',
                  'bg-primary/10 text-primary'
                )}
              >
                内置
              </Badge>
            )}
          </div>
          
          {/* Category Badge */}
          {assistant.category && !compact && (
            <div className="mb-1">
              <Badge 
                className={cn(
                  'px-2 py-0.5 text-xs font-medium',
                  categoryColor
                )}
              >
                {categoryLabel}
              </Badge>
            </div>
          )}

          {/* Description */}
          {!compact && (
            <div className="text-xs text-muted-foreground/80 line-clamp-2 leading-relaxed">
              {assistant.description}
            </div>
          )}
          
          {/* Stats */}
          {!compact && assistant.sessionCount !== undefined && assistant.sessionCount > 0 && (
            <div className="text-xs text-muted-foreground/60 mt-1">
              {assistant.sessionCount} 个会话
            </div>
          )}
        </div>

        {/* Enhanced Favorite Button */}
        {onToggleFavorite && (
          <div
            role="button"
            tabIndex={0}
            className={cn(
              'opacity-0 group-hover:opacity-100 transition-all',
              'inline-flex items-center justify-center rounded-full',
              'hover:bg-yellow-500/10 hover:scale-110',
              'cursor-pointer shrink-0',
              'shadow-sm',
              assistant.isFavorite && 'opacity-100',
              compact ? 'h-6 w-6' : 'h-8 w-8'
            )}
            onClick={(e) => {
              e.stopPropagation();
              onToggleFavorite(assistant.id);
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                e.stopPropagation();
                onToggleFavorite(assistant.id);
              }
            }}
          >
            <Star
              className={cn(
                compact ? 'w-3.5 h-3.5' : 'w-4 h-4',
                'transition-all',
                assistant.isFavorite && 'fill-yellow-500 text-yellow-500 drop-shadow-sm'
              )}
            />
          </div>
        )}
      </div>
    </button>
  );
}

